﻿using System;
using System.Collections.Generic;
using System.IO;
using ProtoBuf;
using GeneralDFS.Common.IO;

namespace GeneralDFS.DataEntity.IO
{
    [ProtoContract]
    [Serializable]
    public class FileNodeInfo : NodeBase
    {
        [ProtoMember(1)]
        public FileBlockInfo[] Blocks { set; get; }

        [ProtoMember(2,IsRequired = true)]
        public long Length { get; set; }

        public override bool IsDirectory()
        {
            return false;
        }

        public FileNodeInfo() { }

        public FileNodeInfo(String fileName, String path, long createTime, String createrName, long length, DirectoryNodeInfo parent, int blockSize)
        {
            base.Name=fileName;
            base.FullPath = path;
            base.CreateTime = createTime;
            base.CreaterName=createrName;
            base.Parent = parent;
            this.Length = length;
            Blocks = 0 == Length % blockSize ? new FileBlockInfo[Length / blockSize] : new FileBlockInfo[Length / blockSize + 1];
        }

        public static FileNodeInfo CreateFile(String path)
        {
            return new FileNodeInfo { FullPath = path, Blocks = new FileBlockInfo[0],CreaterName = "System", CreateTime = DateTime.Now.ToFileTime(), LastUpdateTime = DateTime.Now.ToFileTime(), Length = 4096, Name = PathHelper.FileName(path) };
        }

        public void InitBlocks()
        {
            if (Length != 0&&Blocks!=null)
            {
                for (int i = 0; i < Blocks.Length; i++)
                {
                    Blocks[i]=new FileBlockInfo();
                }
            }
        }

        public override void WriteToBinary(BinaryWriter binaryWriter)
        {
            binaryWriter.Write(Blocks.Length);
            foreach (var fileBlockInfo in Blocks)
            {
                fileBlockInfo.WriteToBinary(binaryWriter);
            }
            binaryWriter.Write(Length);
            base.WriteToBinary(binaryWriter);
        }

        public override NodeBase ReadFromBinary(BinaryReader binaryReader)
        {
            var length = binaryReader.ReadInt32();
            Blocks=new FileBlockInfo[length];
            for (int i = 0; i < length; i++)
            {
                Blocks[i]=new FileBlockInfo();
                Blocks[i].ReadFromBinary(binaryReader);
            }
            Length = binaryReader.ReadInt64();
            return base.ReadFromBinary(binaryReader);
        }
    }
}